<template>
  <div class="user-management-container">
    <h1>{{ $t("menu.userManagement") }}</h1>

    <!-- 查询条件 -->
    <el-card class="filter-container">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item :label="$t('user.status')">
          <el-select v-model="queryParams.status" placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option :label="$t('user.statusOptions.enabled')" value="1" />
            <el-option :label="$t('user.statusOptions.disabled')" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">{{
            $t("common.search")
          }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户表格 -->
    <el-card class="table-container">
      <el-table v-loading="loading" :data="userList" border style="width: 100%">
        <el-table-column prop="id" :label="$t('user.id')" width="80" />
        <el-table-column
          prop="username"
          :label="$t('user.username')"
          width="120"
        />
        <el-table-column prop="email" :label="$t('user.email')" width="180" />
        <el-table-column prop="phone" :label="$t('user.phone')" width="150" />
        <el-table-column prop="address" :label="$t('user.address')" />
        <el-table-column prop="status" :label="$t('user.status')" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '1' ? 'success' : 'danger'">
              {{
                scope.row.status === "1"
                  ? $t("user.statusOptions.enabled")
                  : $t("user.statusOptions.disabled")
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('common.operation')"
          width="150"
          fixed="right"
        >
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">
              {{ $t("common.edit") }}
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              {{ $t("common.delete") }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="$t(dialogType === 'edit' ? 'user.editUser' : 'user.createUser')"
      width="500px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
      >
        <el-form-item :label="$t('user.username')" prop="username">
          <el-input v-model="userForm.username" />
        </el-form-item>
        <el-form-item :label="$t('user.email')" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item :label="$t('user.phone')" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>
        <el-form-item :label="$t('user.address')" prop="address">
          <el-input v-model="userForm.address" />
        </el-form-item>
        <el-form-item :label="$t('user.status')" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio label="1">{{
              $t("user.statusOptions.enabled")
            }}</el-radio>
            <el-radio label="0">{{
              $t("user.statusOptions.disabled")
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">{{
            $t("common.cancel")
          }}</el-button>
          <el-button type="primary" @click="submitForm">{{
            $t("common.submit")
          }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { getUserList, removeUserById } from "@/services/user";
import { ElMessage, ElMessageBox } from "element-plus";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

// 查询参数
const queryParams = reactive({
  status: "",
});

// 表格数据
const userList = ref([]);
const loading = ref(false);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 对话框相关
const dialogVisible = ref(false);
const dialogType = ref("edit"); // edit or create
const userForm = reactive({
  id: null,
  username: "",
  email: "",
  phone: "",
  address: "",
  status: "1",
});
const userFormRef = ref(null);
const userRules = {
  username: [
    {
      required: true,
      message: () => t("user.username") + "不能为空",
      trigger: "blur",
    },
  ],
  email: [
    {
      required: true,
      message: () => t("user.email") + "不能为空",
      trigger: "blur",
    },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
  phone: [
    {
      required: true,
      message: () => t("user.phone") + "不能为空",
      trigger: "blur",
    },
  ],
};

// 初始化
onMounted(() => {
  fetchUserList();
});

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true;
  try {
    const res = await getUserList(queryParams);
    if (res.code === "200") {
      userList.value = res.data;
      total.value = res.data.length;
      ElMessage.success(res.message);
    } else {
      ElMessage.error(res.message || "获取用户列表失败");
    }
  } catch (error) {
    ElMessage.error("获取用户列表失败");
  } finally {
    loading.value = false;
  }
};

// 查询按钮
const handleQuery = () => {
  currentPage.value = 1;
  fetchUserList();
};

// 编辑用户
const handleEdit = (row) => {
  dialogType.value = "edit";
  userForm.id = row.id;
  userForm.username = row.username;
  userForm.email = row.email;
  userForm.phone = row.phone;
  userForm.address = row.address;
  userForm.status = row.status;
  dialogVisible.value = true;
};

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm(t("user.deleteConfirm"), t("user.deleteUser"), {
    confirmButtonText: t("common.confirm"),
    cancelButtonText: t("common.cancel"),
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await removeUserById(row.id);
        if (res.code === "200") {
          ElMessage.success(res.message);
          fetchUserList();
        } else {
          ElMessage.error(res.message || "删除失败");
        }
      } catch (error) {
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {});
};

// 提交表单
const submitForm = async () => {
  if (!userFormRef.value) return;

  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      // 这里应该调用保存用户的API
      // 由于没有提供保存用户的API，这里只是模拟
      ElMessage.success(dialogType.value === "edit" ? "编辑成功" : "创建成功");
      dialogVisible.value = false;
      fetchUserList();
    }
  });
};

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchUserList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchUserList();
};
</script>

<style scoped>
.user-management-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
